<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-row>
          <el-col :span="5">
            <p @click="changeDialogVisible">新建文件夹</p>
          </el-col>
          <el-col :span="5">
            <p @click="changeFrameVisible">选择卷名</p>
          </el-col>
          <el-col :span="5">
            <p @click="changeWindowVisible">开始扫描</p>
          </el-col>
          <el-col :span="5">
            <p @click="changeBoxVisible">分类判断</p>
          </el-col>
          <el-col :span="4">
            <p @click="openFilePicker">选择图片</p>
            <input type="file" ref="fileInput" @change="handleFileSelect" multiple hidden />
          </el-col>
        </el-row>
      </el-header>
     <el-container>
        <el-aside>
          <el-col>
            <el-menu router class="col" active-text-color="#ffd04b" background-color="#545c64" text-color="#fff">
              <el-sub-menu @click="operateFile">
                <template #title>操作文件夹（卷名）：{{ $store.state.UserNameId }}</template>
                <el-menu-item index="one" @click="One">
                  <template #title>干部履历表</template>
                </el-menu-item>
                <el-menu-item index="two" @click="Two">
                  <template #title>自传材料</template>
                </el-menu-item>
                <el-menu-item index="three" @click="Three">
                  <template #title>鉴定、考核材料</template>
                </el-menu-item>
              <el-sub-menu index="1">
                <template #title>
                  <span>学历学位、职称、学术、培训等材料</span>
                </template>
                <el-menu-item index="fourA" @click="FourA">
                  <template #title>4-1 学历学位材料</template>
                </el-menu-item>
                <el-menu-item index="fourB" @click="FourB">
                  <template #title>4-2 专业技术职务材料</template>
                </el-menu-item>
                <el-menu-item index="fourC" @click="FourC">
                  <template #title>4-3 科研学术材料</template>
                </el-menu-item>
                <el-menu-item index="fourD" @click="FourD">
                  <template #title>4-4 培训材料</template>
                </el-menu-item>
              </el-sub-menu>
              <el-menu-item index="five" @click="Five">
                  <template #title>政审材料</template>
              </el-menu-item>
                <el-menu-item index="six" @click="Six">
                  <template #title>党团材料</template>
                </el-menu-item>
                <el-menu-item index="seven" @click="Seven">
                  <template #title>奖励材料</template>
                </el-menu-item>
                <el-menu-item index="eight" @click="Eight">
                  <template #title>处分材料</template>
                </el-menu-item>
              <el-sub-menu index="9">
                <template #title>
                  <span>工资、任免、出国、会议等材料</span>
                </template>
                <el-menu-item index="nineA" @click="NineA">
                  <template #title>9-1 工资材料</template>
                </el-menu-item>
                <el-menu-item index="nineB" @click="NineB">
                  <template #title>9-2 任免材料</template>
                </el-menu-item>
                <el-menu-item index="nineC" @click="NineC">
                  <template #title>9-3 出国（境）审批材料</template>
                </el-menu-item>
                <el-menu-item index="nineD" @click="NineD">
                  <template #title>9-4 会议代表材料</template>
                </el-menu-item>
              </el-sub-menu>
              <el-menu-item index="ten" @click="Ten">
                  <template #title>其他材料</template>
                </el-menu-item>
              </el-sub-menu>
            </el-menu>
          </el-col>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
  <Dialog :dialogValue="dialogVisible" @ChangeDialogVisible="ChangeDialogVisible" @CreateFolder="CreateFolder" />
  <Window :windowValue="windowVisible" @ChangeWindowVisible="ChangeWindowVisible"
    @handleFileSelect="handleFileSelect" />
  <Box :boxValue="boxVisible" @ChangeBoxVisible="ChangeBoxVisible" />
  <Box1 :frameValue="frameVisible" @ChangeFrameVisible="ChangeFrameVisible" />
</template>


<script setup>
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { createFolder, chooseFile } from '../../api/create_folder'
import { sendPhoto } from '../../api/photo'
import { useWebSocket } from '../../utils/webscoket'
import { Inquire,Search,clickItem } from '../../api/inquire'
import { ElMessage } from 'element-plus'

import Dialog from '../../components/Dialog.vue'
import Window from '../../components/Window.vue'
import Box from '../../components/Box.vue'
import Box1 from '../../components/Box1.vue'

const store = useStore()
const router = useRouter()
const fileArr = reactive([])
const photo = ref(null)
const fileInput = ref(null)
const folderName = ref('个人文件夹(卷)')
const dialogVisible = ref(false)
const windowVisible = ref(false)
const boxVisible = ref(false)
const frameVisible = ref(false)


const changeDialogVisible = () => {
  dialogVisible.value = true
}

const changeBoxVisible = () => {
  console.log(store.state.class)
      if(store.state.class.value.category !== undefined && store.state.class.value.fileName !== undefined){
        boxVisible.value = true
      }else{
        ElMessage.error('请按顺序操控程序')
      }
}

const operateFile = async() => {
      const res = await Inquire(store.state.UserNameId)
      console.log(res)
}

const changeFrameVisible = async () => {
  frameVisible.value = true
  const res = await chooseFile()
  console.log(res.data)
  store.commit('SendUserName', res.data)
}

function handleMessage(e) {
  if (e.data.length > 10) {
    const aList = JSON.parse(e.data).data
    console.log(aList)
    store.commit('sendBase64List', aList)
    // localStorage.setItem('ce',aList)
    // a.push(localStorage.getItem('ce'))
    // const alist = base64ArrayToImageArray(aList)
    // console.log(alist)
    // store.commit('sendPhotoList',alist)


  } else {
    console.log(e.data)
  }

}
const changeWindowVisible = async () => {
  // console.log(store.state.ScanId)
  if (store.state.UserNameId !== '') {
    const ws = useWebSocket(handleMessage)
  }


  // ws.send('你好')可以在建立连接之后在发送
  // console.log('11')
  windowVisible.value = true

  // const aList = base64ArrayToImageArray(a)
  // console.log(aList)
  // store.commit('sendPhotoList',aList)
  // const a = []
  // a.push(localStorage.getItem('ce'))
  // const alist = base64ArrayToImageArray(a)
  // console.log(alist)
  // store.commit('sendPhotoList',alist)
}

//将base64图片数组转化为普通图片数组
// const base64ArrayToImageArray = (base64Array) => {
//    const imageUrls = [];

//    base64Array.forEach(base64 => {
//       //移除base64字符串前缀
//       const base64Prefix = "data:image/jpeg;base64,"
//       if (base64.startsWith(base64Prefix)) {
//          base64 = base64.substring(base64Prefix.length)
//       }

//       //解码base64字符串并转换为Blob对象
//       const blob = new Blob([base64], { type: 'image/jpeg' })

//       //为Blob对象创建一个临时的URL
//       const imageUrl = URL.createObjectURL(blob)

//       //将图片URL添加到数组中
//       imageUrls.push(imageUrl)
//    })

//    return imageUrls;
// } 

const ChangeDialogVisible = () => {
  dialogVisible.value = false
}

const ChangeWindowVisible = () => {
  windowVisible.value = false
}

const ChangeBoxVisible = () => {
  boxVisible.value = false
}

const ChangeFrameVisible = () => {
  frameVisible.value = false
}

const CreateFolder = async (file) => {
  // try{
  // console.log('文件创建成功')
  const res = await createFolder(file)

  console.log(res)
     if(res.data === true){
        ElMessage({
            message: '文件夹创建成功，请选择卷名',
            type: 'success'
        })
        router.push('/scan')
      }else{
        ElMessage.error({
            message: '文件夹创建失败，请重新创建'
        })
      }
  //  const scan = res.data
  //  store.commit('SendScan',res.data)
  // }
  // catch(error){
  //   console.log(error)
  // }
}

const openFilePicker = () => {
  fileInput.value.click()
}

const handleFileSelect = async (e) => {
  const files = Array.from(e.target.files); // 将FileList转换为数组
  console.log(files)
  // 初始化一个空数组来存储Base64字符串
  const base64Images = [];

  // 使用Promise.all来并行读取所有文件
  const readPromises = files.map(file => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        base64Images.push(reader.result);
        resolve();
      };
      reader.onerror = error => {
        reject(new Error(`Error reading file ${file.name}:${error}`));
      };
      reader.readAsDataURL(file);
    });
  });

  try {
    // 使用await等待所有Promise执行完成
    await Promise.all(readPromises);
    // console.log(a)
    console.log(base64Images.length)
    // 所有文件读取完成后，发送所有Base64字符串
    const res = await sendPhoto(base64Images);
    console.log(res.data);
  } catch (err) {
    // 在控制台打印错误信息
    console.log(err);
    // 可以根据实际需求进行错误处理，例如提示用户或返回错误信息
  }
};


const One = async () => {
  // const a = [store.state.UserNameId, '一类：履历类材料']
  
  const res = await Search('1')
  console.log(res.data)
  // const List1 = res.data
  // console.log(List1)
  store.commit('sendName',res.data)
  // console.log(store.state.Name)
}
const Two = async () => {
  // const b = [store.state.UserNameId, '二类：自传材料']
  const res = await Search('2')
  console.log(res)
  store.commit('sendName',res.data)
}
const Three = async () => {
  // const c = [store.state.UserNameId, '三类：鉴定、考核材料']
  const res = await Search('3')
  console.log(res)
  store.commit('sendName',res.data)
}
const FourA = async () => {
  // const d1 = [store.state.UserNameId, '4-1类：学历学位材料']
  const res = await Search('4a')
  console.log(res)
  store.commit('sendName',res.data)
}
const FourB = async () => {
  // const d2 = [store.state.UserNameId, '4-2类：专业技术职务材料']
  const res = await Search('4b')
  console.log(res)
  store.commit('sendName',res.data)
}
const FourC = async () => {
  // const d3 = [store.state.UserNameId, '4-3类：科研学术材料']
  const res = await Search('4c')
  console.log(res)
  store.commit('sendName',res.data)
}
const FourD = async () => {
  // const d4 = [store.state.UserNameId, '4-4类：培训材料']
  const res = await Search('4d')
  console.log(res)
  store.commit('sendName',res.data)
}
const Five = async () => {
  // const e = [store.state.UserNameId, '五类：政审材料']
  const res = await Search('5')
  console.log(res)
  store.commit('sendName',res.data)
}
const Six = async () => {
  // const f = [store.state.UserNameId, '六类：党团类材料']
  const res = await Search('6')
  console.log(res)
  store.commit('sendName',res.data)
}
const Seven = async () => {
  // const g = [store.state.UserNameId, '七类：奖励类材料']
  const res = await Search('7')
  console.log(res)
  store.commit('sendName',res.data)
}
const Eight = async () => {
  // const h = [store.state.UserNameId, '八类：处分材料']
  const res = await Search('8')
  console.log(res)
  store.commit('sendName',res.data)
}
const NineA = async () => {
  // const i1 = [store.state.UserNameId, '9-1类：工资材料']
  const res = await Search('9a')
  console.log(res)
  store.commit('sendName',res.data)
}
const NineB = async () => {
  // const i2 = [store.state.UserNameId, '9-2类：任免材料']
  const res = await Search('9b')
  console.log(res)
  store.commit('sendName',res.data)
}
const NineC = async () => {
  // const i3 = [store.state.UserNameId, '9-3类：出国（境）审批材料']
  const res = await Search('9c')
  console.log(res)
  store.commit('sendName',res.data)
}
const NineD = async () => {
  // const i4 = [store.state.UserNameId, '9-4类：会议代表材料']
  const res = await Search('9d')
  console.log(res)
  store.commit('sendName',res.data)
}
const Ten = async () => {
  // const j = [store.state.UserNameId, '十类：其他材料']
  const res = await Search('10')
  console.log(res)
  store.commit('sendName',res.data)
}

// const ClickItem = async() => {
//   const res = await clickItem('4556')
//   console.log(res)
// }

</script>

<style scoped>
.el-container {
  width: 100%;
  /* height: 100vh; */
}

.el-header {
  background-color: #333;
  height: 60px;
}

.el-header .el-row {
  margin: 20px auto;
  width: 1200px;
  color: #A4B0A4;
  /* background-color: pink; */
  font-size: 20px;
  cursor: pointer;
}

.col {
  width: 300px;
  height: calc(100vh - 60px);
  /* height: 100vh; */
  background-color: #545c64;
  color: #fff;
}
</style>
